<?php

namespace mpend\modules\passport\controllers;

use Yii;
use mpend\components\Controller;
use mpend\modules\passport\models\LoginForm;
use mpend\modules\passport\models\MpLoginForm;
use common\helpers\ArrayHelper;

/**
 * 账号登录
 * 
 * @author emhome <emhome@163.com>
 * @since 2.0
 */
class LoginController extends Controller {

    /**
     * @inheritdoc
     */
    protected function rules() {
        return null;
    }

    /**
     * @inheritdoc
     */
    protected function verbs() {
        return [
            '*' => ['POST'],
        ];
    }

    /**
     * 帐号密码登录
     * @inheritdoc
     */
    public function actionIndex() {
        $model = new LoginForm();
        $params = Yii::$app->request->post();
        $ms = ArrayHelper::remove($params, 'ms');
        $attributes = $params;
        if ($ms) {
            /* @var $security \common\base\Security */
            $security = Yii::$app->security;
            foreach ($params as $k => $v) {
                $attributes[$k] = $security->decryptDataByKey($v);
            }
        }
        if (!$model->load($attributes, '')) {
            parent::error('请输入帐号和密码信息');
        }
        $model->token = $this->token;
        return $model->login();
    }

    /**
     * 小程序登录
     * @inheritdoc
     */
    public function actionMp() {
        $model = new MpLoginForm();
        $model->user_id = $this->uid;
        if (!$model->load(Yii::$app->request->post(), '')) {
            parent::error('请设置用户信息');
        }
        $model->token = $this->token;
        return $model->login();
    }

    /**
     * {@inheritdoc}
     */
    public function afterAction($action, $result) {
        $uid = ArrayHelper::getValue($result, 'id');
        if ($uid && !$this->token->bindUser($uid)) {
            parent::error('登录失败', $this->token->firstErrors);
        }
        return parent::afterAction($action, $result);
    }

}
